﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UYD_WCS.DBUtility;

namespace UYD_WCS_AS_AGV_Controller
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            bool ret = false;
            Mutex ContestMutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
            if (ret)
            {
                AppDomain myCurrentDomain = AppDomain.CurrentDomain;
                myCurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(myCurrentDomain_UnhandledException);


                

                //获取欲启动进程名
                string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            ////获取版本号 
            //CommonData.VersionNumber = Application.ProductVersion; 
            //检查进程是否已经启动，已经启动则显示报错信息退出程序。 
            if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
            {
                MessageBox.Show("系统程序已经运行！", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
                return;
            }

            try
                {
                    //string strDbFile = "C:\\AGV_Controller_XJ\\db.db";
                string strDbFile = Application.StartupPath + "\\db.db";
                string connStr = @"Data Source=" + strDbFile + ";Pooling = true; FailIfMissing = false;";
                DbHelperSQLite.connectionString = connStr;
                if (File.Exists(strDbFile))
                {

                }
                else
                {
                    FileStream fs= File.Create(strDbFile);
                    fs.Close();
                    Thread.Sleep(1000);
                    //string strCreateTableSql = " CREATE TABLE W_TASK_AGV (TASK_ID BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY, TASK_NO VARCHAR(30),TASK_FLAG VARCHAR(30),TASK_DATE VARCHAR(20),GET_LOC VARCHAR(20),SET_LOC VARCHAR(20), TASK_STATUS_CODE INT ); ";
                    //DbHelperSQLite.ExecuteSql(strCreateTableSql);

                    string strCreateTableSql = "  CREATE TABLE W_POS( LOC_NO DECIMAL(10, 10) PRIMARY KEY,LOC_NO_TYPE STRING(5), X DECIMAL(10, 10),Y DECIMAL(10, 10),W DECIMAL(10, 10),Z DECIMAL(10, 10)); ";
                    
                        DbHelperSQLite.ExecuteSql(strCreateTableSql);

                    strCreateTableSql = @"CREATE TABLE WCS_AGV_TASK (
                                            id            INTEGER      PRIMARY KEY AUTOINCREMENT,
                                            taskCode      VARCHAR,
                                            reqCode       VARCHAR,
                                            reqTime       VARCHAR,
                                            startPosition VARCHAR,
                                            endPosition   VARCHAR,
                                            priority      VARCHAR,
                                            taskStatus    INTEGER,
                                            startLocGroup INTEGER,
                                            startLocColl  INTEGER,
                                            startLocFloor INTEGER,
                                            endLocGroup   INTEGER,
                                            endLocColl    INTEGER,
                                            endLocFloor   INTEGER,
                                            startAgvLoc   VARCHAR (32),
                                            endAgvLoc     VARCHAR (32) 
                                        );
                                        ";
                    DbHelperSQLite.ExecuteSql(strCreateTableSql);

                    strCreateTableSql = @"CREATE TABLE WCS_AGV_LOC (
                                                WCS_LOC      VARCHAR,
                                                AGV_LOC       VARCHAR,
                                                LOC_GROUP       int,
                                                LOC_COLL       int,
                                                LOC_FLOOR       int
                                            );";
                    DbHelperSQLite.ExecuteSql(strCreateTableSql);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "错误");
            }

            //初始化供WCS调用的服务
            BasicInfo.Init();

            Application.Run(new FrmMain());
            
        }
            else
            {
                //MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行，请不要同时运行多个本程序。\n\n这个程序即将退出。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                // 提示信息，可以删除。   

                Application.ExitThread();

                System.Environment.Exit(0);
                Application.Exit();//退出程序   

            }

}

        private static string HexStringToString(string hs, Encoding encode)
        {
            //以%分割字符串，并去掉空字符
            string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] b = new byte[chars.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < chars.Length; i++)
            {
                b[i] = Convert.ToByte(chars[i], 16);
            }
            //按照指定编码将字节数组变为字符串
            return encode.GetString(b);
        }

        /// <summary>
        /// 字符串转16进制字节数组 
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] ToHexByteArray(string hexString)
        {
            hexString = CheakHexString(hexString);
            hexString = hexString.Replace(" ", "");
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        /// <summary>
        /// 校验16进制字符串
        /// </summary>
        /// <param name="strBuffHex">16进制字符串</param>
        /// <returns></returns>
        private static string CheakHexString(string strBuffHex)
        {
            strBuffHex = strBuffHex.Trim();     //去除前后空字符
            strBuffHex = strBuffHex.Replace(',', ' ');  //去掉英文逗号
            strBuffHex = strBuffHex.Replace('，', ' '); //去掉中文逗号
            strBuffHex = strBuffHex.Replace("0x", "");  //去掉0x
            strBuffHex = strBuffHex.Replace("0X", "");  //去掉0X
            strBuffHex = Regex.Replace(Regex.Replace(strBuffHex, @"(?i)[^a-f\d\s]+", ""), "\\w{3,}", m => string.Join(" ", Regex.Split(m.Value, @"(?<=\G\w{2})(?!$)").Select(x => x.PadLeft(2, '0')).ToArray())).ToUpper();
            return strBuffHex;
        }

        static void myCurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string error = "";
            try
            {
                Exception unhandeld = (Exception)e.ExceptionObject;
                error = "++++++++++++++++++++++++++++UNHANDELD EXCEPTION++++++++++++++++++++++++++++++++++++++++++++\r\n";
                error += DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss:fff") + "\r\n";
                error += "CLS Terminating = " + e.IsTerminating.ToString() + "\r\n";
                error += "------------------------------------------------------------------------------------------\r\n";
                error += "Exception:\r\n";
                error += "Message: " + unhandeld.Message + "\r\n";
                error += "Source:  " + unhandeld.Source + "\r\n";
                error += "StackTrace:  " + unhandeld.StackTrace + "\r\n";
                error += "==========================================================================================\r\n";
                error += "Innerexception Message: \r\n";
                if (unhandeld.InnerException != null)
                {
                    error += unhandeld.InnerException.Message + "\r\n";
                    error += "Source:  " + unhandeld.InnerException.Source + "\r\n";
                    error += "StackTrace:  " + unhandeld.InnerException.StackTrace + "\r\n";
                }
                error += "==========================================================================================\r\n";
                using (StreamWriter writer = new StreamWriter("unhandled.txt", true))
                {
                    writer.WriteLine(error);
                    writer.Flush();
                    writer.Close();
                }
            }
            catch (Exception more)
            {
                //even more misery
                MessageBox.Show(error + " additional problem: " + more.Message);
            }
            finally
            {
                //cleanup 
                if (e.IsTerminating)
                {
                    MessageBox.Show(error);
                }
            }
        }

    }
}
